package comits.web.client.servlets.demo;
import java.io.IOException;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import comits.business.tiers.dao.CommandeDAO;
import comits.business.tiers.dao.CommandeDAOImpl;
import comits.business.tiers.dao.EmployeDAO;
import comits.business.tiers.dao.EmployeDAOImpl;
import comits.business.tiers.dao.HistolignecmdDAO;
import comits.business.tiers.dao.HistolignecmdDAOImpl;
import comits.business.tiers.dao.LigneCmdDAO;
import comits.business.tiers.dao.LigneCmdDAOImpl;
import comits.business.tiers.dao.OrdreEntreeDAO;
import comits.business.tiers.dao.OrdreEntreeDAOImpl;
import comits.business.tiers.dao.ProduitStockeDAO;
import comits.business.tiers.dao.ProduitStockeDAOImpl;
import comits.business.tiers.metiers.Commande;
import comits.business.tiers.metiers.Depot;
import comits.business.tiers.metiers.Employe;
import comits.business.tiers.metiers.LigneCmd;
import comits.business.tiers.metiers.OrdreEntree;
import comits.business.tiers.metiers.ProduitStocke;
import comits.business.tiers.rp.tasks.ws.ControleurEntreeStock;


/**
 * 
 * @author assia
 */
public class EntreeStockServlet extends HttpServlet {
	
	private static final long serialVersionUID = 7526928611471348888L;
	
	private Date date;

	public void init() throws ServletException {
		date = new Date();
	}

	/**
	 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
	 * methods.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 *             if a servlet-specific error occurs
	 * @throws IOException
	 *             if an I/O error occurs
	 */
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	// <editor-fold defaultstate="collapsed"
	// desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
	/**
	 * Handles the HTTP <code>GET</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 *             if a servlet-specific error occurs
	 * @throws IOException
	 *             if an I/O error occurs
	 */
	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		
		String action = request.getParameter("action");
		
		if (action.equals("Visualiser bon de livraison")) {
			CommandeDAO cmd=new CommandeDAOImpl();
			LigneCmdDAO Lcmd=new LigneCmdDAOImpl();
			Date datejour=new Date();
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			int codecoli=Integer.parseInt(request.getParameter("codeColi"));
			int codebl=Integer.parseInt(request.getParameter("codeBL"));
			String datejr = df.format(datejour).toString();
			String stutcmd = cmd.getStatutCmd(codebl);
			request.setAttribute("statutcmd",stutcmd);
			request.setAttribute("codecoli", codecoli);
			request.setAttribute("numcmd", codebl);		
			request.setAttribute("datejour", datejr);
			ControleurEntreeStock CES=new ControleurEntreeStock();
			List<LigneCmd> listLignecmd=Lcmd.getListEncoursCmd(codecoli);
			List<Commande> listcmd=cmd.getListNumCmd(codecoli);
			String expediteur=cmd.getExpediteurCmd(codebl);
			Integer numexp=cmd.getNumExpCmd(codebl);
			Date datecreation=cmd.getDateCreationCmd(codebl);
			Date datereceptioncmd=cmd.getDateRecepCmd(codebl);
			request.setAttribute("expediteur", expediteur);
			request.setAttribute("numexp",numexp );
			request.setAttribute("datecreation",datecreation);
			request.setAttribute("datereceptioncmd",datereceptioncmd );
			request.setAttribute("listLigneCommande",listLignecmd);
			request.setAttribute("listcommande",listcmd);
			getServletContext().getRequestDispatcher("/EntreeEnStock.jsp").forward(request, response);

		}
			else if (action.equals("Enregistrer")){
			CommandeDAO cmd=new CommandeDAOImpl();
			LigneCmdDAO lignecmd=new LigneCmdDAOImpl();
			HistolignecmdDAO histoLigneCmd = new HistolignecmdDAOImpl();
			String statu_commande = (String)request.getParameter("statu_commande");
			Integer numcmd = Integer.parseInt(request.getParameter("numcmd"));
//			String expediteur = (String)request.getParameter("expediteur");
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Date datecreation = null;
			Date datereceptioncmd = null;
			try {
				datecreation = df.parse(request.getParameter("datecreation"));
				datereceptioncmd = df.parse(request.getParameter("datereceptioncmd"));
			} catch (ParseException e) {
				datereceptioncmd=new Date();
				e.printStackTrace();
			}
			String avis_comande = (String)request.getParameter("avis_comande");
			List<LigneCmd> listlign=lignecmd.getListEncoursCmd(numcmd);
			int i=0;
			for (LigneCmd ligne : listlign) {
				Integer quantite = Integer.parseInt(request.getParameter("qte"+i).trim());
				Integer qteManquante =  Integer.parseInt(request.getParameter("qteManquante"+i).trim());
				Integer qtemauvaisetat =  Integer.parseInt(request.getParameter("qtemauvaisetat"+i).trim());
				String statu_Ligne_commande = request.getParameter("statu_Ligne_commande"+i);
				String motif_commande = request.getParameter("motif_commande"+i);
				Integer numpdt=Integer.parseInt(request.getParameter("numpdt"+i));
				Date datereception = new Date();
//				Date datereception = null;
				Date datestatut = null;
				try {
					datereception = df.parse(request.getParameter("datereception"+i));
					datestatut = df.parse(request.getParameter("datestatut"+i));
				} catch (ParseException e) {
					datereceptioncmd=new Date();
					e.printStackTrace();
				}
//				ligne.setQuantiteManquante(qteManquante);
//				ligne.setQuantiteMauvaisEtat(qtemauvaisetat);
//				ligne.setStatut(statu_Ligne_commande);
//				ligne.setMotif(motif_commande);
//				ligne.setDateReception(datereception);
				lignecmd.updateLigneCmd(qteManquante, qtemauvaisetat, statu_Ligne_commande, datestatut, datereception, numcmd, numpdt, motif_commande);
				histoLigneCmd.saveHistoLCmd(numcmd, numpdt, quantite, qteManquante, qtemauvaisetat, datereception, statu_Ligne_commande, datestatut, motif_commande);
				i++;
			}
		    cmd.updateCommandeRecu(statu_commande, datereceptioncmd, avis_comande, numcmd);
			getServletContext().getRequestDispatcher("/modifValider.jsp").forward(request, response);
			
		} else if (action.equals("Afficher bon d'entree")){
				
				CommandeDAO cmd = new CommandeDAOImpl();
				LigneCmdDAO lignecmd = new LigneCmdDAOImpl();
				OrdreEntreeDAO ordre = new OrdreEntreeDAOImpl();
				EmployeDAO employe= new EmployeDAOImpl();
				ProduitStockeDAO prdtstocke = new ProduitStockeDAOImpl();
				ControleurEntreeStock controleurEntrestock = new ControleurEntreeStock();
				
				Integer numcmd = Integer.parseInt(request.getParameter("numcmd"));
				List<LigneCmd> listlign=lignecmd.getListEncoursCmd(numcmd);
				List<LigneCmd> lstlignecmd = new ArrayList<LigneCmd>();
				List<Commande> listcmd = cmd.getListNumCmd(numcmd);
				
				DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				String datejr = df.format(new Date()).toString();
				String expediteur = cmd.getExpediteurCmd(numcmd);
				Integer numexp=cmd.getNumExpCmd(numcmd);
				String destinatiare =cmd.getDestinataireCmd(numcmd);
				Integer numDest=cmd.getNumDestinataireCmd(numcmd);
				Integer numEmploye=null;
				String nomEmploye="";
				if(ordre.isExistCmd(numcmd)){
				numEmploye= ordre.getNumEmploye(numcmd);
				 nomEmploye=employe.getNomEmploye(numEmploye);
				}
				
				List<ProduitStocke> listproduitStocke = prdtstocke.recupListPdtDeBoutique(destinatiare, numDest);
				System.out.println("list produit stocke is ==================" +listproduitStocke);
				List<Object> listNumcmd = controleurEntrestock.afficherListeOrdreEntree(numexp);
				List<Employe> listEmp = controleurEntrestock.listEmpSite(destinatiare, numDest);
				
				int i=0;
				for (LigneCmd ligne : listlign) {
					String statutLigncmd=ligne.getStatut();
					Integer numprdt=ligne.getNumPdt();
					Integer qte= ligne.getQuantite();
					Integer qtemqt = ligne.getQuantiteManquante();
					Integer qteMvaisEtat =ligne.getQuantiteMauvaisEtat();
					try {
						@SuppressWarnings("unused")
						Date dateordreEntre= df.parse(datejr);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}	
					Integer qtecalculer= qte-qtemqt-qteMvaisEtat;
					if((statutLigncmd.equals("Livree")) || ((qtecalculer != qte) &&(statutLigncmd.equals("Stockage"))) ){
						lstlignecmd.add(ligne);
					}
//					controleurEntrestock.saveOrdreEntreeCmd(numcmd, numpdt, lst);
					i++;	
				}
			request.setAttribute("nomEmploye", nomEmploye);
			request.setAttribute("numEmploye", numEmploye);
			request.setAttribute("listNumcmd", listNumcmd);
			request.setAttribute("lstlignecmd", lstlignecmd);
			request.setAttribute("listcmd", listcmd);
			request.setAttribute("listproduitStocke", listproduitStocke);
			request.setAttribute("numcmd", numcmd);
			request.setAttribute("expediteur",expediteur );
			request.setAttribute("numexp",numexp);
			request.setAttribute("destinatiare",destinatiare );
			request.setAttribute("numDest",numDest);
			request.setAttribute("dateOrdre",datejr);
			request.setAttribute("listemp",listEmp);
			getServletContext().getRequestDispatcher("/bonreception.jsp").forward(request, response);
			
		} 	else if (action.equals("Retour")){
			
			ControleurEntreeStock CES=new ControleurEntreeStock();
			CommandeDAO cmd=new CommandeDAOImpl();
			LigneCmdDAO Lcmd=new LigneCmdDAOImpl();
			Date datejour=new Date();
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			int numcmd=Integer.parseInt(request.getParameter("numCmd"));
			String datejr = df.format(datejour).toString();
			String stutcmd = cmd.getStatutCmd(numcmd);
			String expediteur=cmd.getExpediteurCmd(numcmd);
			Integer numexp=cmd.getNumExpCmd(numcmd);
			Date datecreation=cmd.getDateCreationCmd(numcmd);
			Date datereceptioncmd=cmd.getDateRecepCmd(numcmd);

			List<LigneCmd> listLignecmd=Lcmd.getListEncoursCmd(numcmd);
			List<Commande> listcmd=cmd.getListNumCmd(numcmd);
		
			request.setAttribute("statutcmd",stutcmd);
			request.setAttribute("codecoli", numcmd);
			request.setAttribute("numcmd", numcmd);		
			request.setAttribute("datejour", datejr);
			request.setAttribute("expediteur", expediteur);
			request.setAttribute("numexp",numexp );
			request.setAttribute("datecreation",datecreation);
			request.setAttribute("datereceptioncmd",datereceptioncmd );
			request.setAttribute("listLigneCommande",listLignecmd);
			request.setAttribute("listcommande",listcmd);
			getServletContext().getRequestDispatcher("/EntreeEnStock.jsp").forward(request, response);
			
		} else if (action.equals("Enregistre ordre d'entree")){
			
//			CommandeDAO cmd=new CommandeDAOImpl();
//			LigneCmdDAO lignecmd=new LigneCmdDAOImpl();
			EmployeDAO employe = new EmployeDAOImpl();
//			HistolignecmdDAO histoLigneCmd = new HistolignecmdDAOImpl();
			Integer numcmd = Integer.parseInt(request.getParameter("numCmd"));
//			String expediteur = (String)request.getParameter("expediteur");
			String manutentionnaire = (String)request.getParameter("Manutentionnaire");
			Integer numManutentionnaire = employe.getNumEmploye(manutentionnaire);
//			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Date dateORdre=new Date();
//			Date datecreation = null;
			OrdreEntreeDAO ordreE = new OrdreEntreeDAOImpl();
			if(ordreE.isExistCmd(numcmd)==false){
				ordreE.saveOrdreECmd(dateORdre, numcmd, numManutentionnaire);
			}
			
			ordreE.updateOrdreEntreeCmd(numManutentionnaire, numcmd);
			getServletContext().getRequestDispatcher("/modifValider.jsp").forward(request, response);
		
		}else if (action.equals("Consulter Ordres d'entree")){
			
			ControleurEntreeStock CEntree = new ControleurEntreeStock();
			OrdreEntreeDAO ordreE= new OrdreEntreeDAOImpl();
			CommandeDAO cmd = new CommandeDAOImpl();
			EmployeDAO employeDao= new EmployeDAOImpl();
			HttpSession session = request.getSession(true);  
			List<Depot> lstDpt = (List<Depot>) session.getAttribute("listDpt");
			int index = ((Integer)session.getAttribute("idLog"))-1;
			String numeroDepot = lstDpt.get(index).getNumDpt().toString();
			Integer numSite = Integer.parseInt(numeroDepot);
			
			//Pour recuperer les ordresd'entree	
			
			Integer numcmd = Integer.parseInt(request.getParameter("numcmd"));
			Integer numeroSite=cmd.getNumDestinataireCmd(numcmd);
			String site =cmd.getDestinataireCmd(numcmd);
			List<Commande> listcmd = cmd.getListCommandeDestinataire(numeroSite, site);
			List<Employe> listempl = employeDao.getListEmploye(site, numeroSite);
			List<OrdreEntree>  listordre = ordreE.getListOrdreEntree();
						
			List<OrdreEntree> listresultat = new ArrayList<OrdreEntree>();
			int i=0;
			for (Commande listecmd : listcmd) {
				int j=0;
				Integer numcommande = listecmd.getNumCmd();
				for(OrdreEntree listeordre: listordre){
					Integer numcommandeordre=listeordre.getNumCmd();
					if(numcommande.intValue()==numcommandeordre.intValue()){
						listresultat.add(listeordre);
					}
					j++;
				}
				i++;	
			}			
			List<Object> listnumcmd = CEntree.afficherListeOrdreEntree(numSite);
			List<OrdreEntree> listOrdre=ordreE.getListOrdreEntree();	
			List<Employe> listEmp = CEntree.listEmpSite(site, numSite);
			
			request.setAttribute("listemp",listEmp);
			request.setAttribute("numSite",numeroSite);
			request.setAttribute("site",site);
			request.setAttribute("listNumCmd",listnumcmd);
			request.setAttribute("listOrdre",listOrdre);
			request.setAttribute("listresultat",listresultat);
			request.setAttribute("listempl",listempl);
			
			getServletContext().getRequestDispatcher("/consulterOrdreEntree.jsp").forward(request, response);
			
		}else if(action.equals("Modifier")){
			
			CommandeDAO cmd = new CommandeDAOImpl();
			OrdreEntreeDAO ordreE = new OrdreEntreeDAOImpl();
			List<OrdreEntree>  listordre = ordreE.getListOrdreEntree();
			EmployeDAO employe = new EmployeDAOImpl();
			Integer numeroSite = Integer.parseInt(request.getParameter("numsite"));
			String site = (String)request.getParameter("site");
			List<Commande> listcmd = cmd.getListCommandeDestinataire(numeroSite, site);
			List<OrdreEntree> lstOrdre=new ArrayList<OrdreEntree>();

			int i=0;
			for (Commande listecmd : listcmd) {
				int j=0;
				Integer numcommande = listecmd.getNumCmd();
				for(OrdreEntree listeordre: listordre){
					Integer numcommandeordre=listeordre.getNumCmd();
					if(numcommande.intValue()==numcommandeordre.intValue()){
						
						lstOrdre.add(listeordre);
					}
					j++;
				}
				i++;	
			}	
			int k=0;
			for (OrdreEntree listord:lstOrdre){
				String manutentionnaire = request.getParameter("Manutentionnaire"+k);
				Integer numempl =employe.getNumEmploye(manutentionnaire);
				Integer numcmd =  Integer.parseInt(request.getParameter("numcmdordre"+k));
				ordreE.updateOrdreEntreeCmd(numempl, numcmd);
			}
			getServletContext().getRequestDispatcher("/modifValider.jsp").forward(request, response);
		
		}else if(action.equals("Quitter")){
			getServletContext().getRequestDispatcher("/accueilEntreeStock.jsp").forward(request, response);
		
		}else if(action.equals("Retour Menu Entree Stock")){
			getServletContext().getRequestDispatcher("/VerificationMarquage.jsp").forward(request, response);
		
		}else if(action.equals("Retour au menu")){
			getServletContext().getRequestDispatcher("/accueilEntreeStock.jsp").forward(request, response);
		
		}else if(action.equals("Enregistrer entree stock")){
			getServletContext().getRequestDispatcher("/VerificationMarquage.jsp").forward(request, response);
		
		}else if(action.equals("Consulter les ordres d'entrees")){
			HttpSession session  = request.getSession();
			String login = (String)session.getAttribute("login");
			String site = (String)session.getAttribute("site");
			
			ControleurEntreeStock CEntreStock = new ControleurEntreeStock();
			List<OrdreEntree> listOrdreSite = CEntreStock.RecupererListeOrdre(site, login);
			List<Employe> listEmp = CEntreStock.getAllEmpSite(site, login);
			request.setAttribute("listOrdreSite",listOrdreSite);
			request.setAttribute("listEmp",listEmp);
			request.setAttribute("site",site);
			getServletContext().getRequestDispatcher("/consulterTousOrdreEntree.jsp").forward(request, response);
		}else if(action.equals("modifier")){
			getServletContext().getRequestDispatcher("/modifValider.jsp").forward(request, response);
		}
	}

	/**
	 * Handles the HTTP <code>POST</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 *             if a servlet-specific error occurs
	 * @throws IOException
	 *             if an I/O error occurs
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	/**
	 * Returns a short description of the servlet.
	 * 
	 * @return a String containing servlet description
	 */
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>
}
